package com.benson.common.upload.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.benson.common.common.entity.ResultPoJo;
import com.benson.common.upload.entity.UploadItem;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * 上传服务
 *
 * @author zhangby
 * @date 28/9/20 12:19 pm
 */
@RequestMapping("/file/upload")
@RestController
@Api(tags = "文件上传服务")
public class UploadController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 图片上传路径
     */
    @Value("${basic-common.upload.file.image:classpath:/static/upload/image}")
    private String imagePath;

    /**
     * 文件上传服务
     * @param file
     * @return
     */
    @PostMapping("/image")
    @ResponseBody
    @ApiOperation(value = "upload image", notes = "", produces = "application/json")
    public ResultPoJo<UploadItem> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ResultPoJo.ok(UploadItem.error());
            }
            /** 判断图片类型 */
            String contentType = file.getContentType();
            if (!contentType.contains("image")) {
                return ResultPoJo.ok(UploadItem.error());
            }
            String fileName = file.getOriginalFilename();
            String filePath = imagePath+ DateUtil.format(new Date(),"/yyyy/MM/");
            //替换项目路径
            //判断文件夹是否为空
            File dest = new File(filePath);
            if (dest.exists()) {
                FileUtil.mkdir(dest);
            }
            String uuid = IdUtil.fastSimpleUUID();
            String imageName = uuid + fileName.substring(fileName.lastIndexOf("."), fileName.length());
            String imagePath = filePath + imageName;
            //上传文件
            FileUtil.writeBytes(file.getBytes(),imagePath.replace("classpath:", ResourceUtils.getURL("classpath:").getPath()));
            /** 获取返回地址 */
            String imgUrl = imagePath.replace("classpath:", "").replace("/static", "");
            return ResultPoJo.ok(UploadItem.ok()
                    .setUid(uuid)
                    .setName(imageName)
                    .setUrl(imgUrl)
                    .setThumbUrl(imgUrl));
        } catch (IOException e) {
            logger.error(e.toString(), e);
        }
        return ResultPoJo.ok(UploadItem.error());
    }

}
